package link.hwx.controller.oa;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import link.hwx.entity.oa.*;
import link.hwx.service.oa.OaAssistanceContractService;
import link.hwx.service.oa.OaInfoService;
import link.hwx.service.u9.AssistanceContractService;
import link.hwx.util.AjaxResult;
import link.hwx.util.CommonSetData;
import link.hwx.util.HttpManager;
import link.hwx.util.IdentityVerifyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Oa合同单接口
 */
@RestController
@RequestMapping("/cx/oa")
public class OaAssistanceContractOpenApi {

    @Autowired
    private AssistanceContractService assistanceContractService;
    @Autowired
    private OaAssistanceContractService oaAssistanceContractService;
    @Autowired
    private OaInfoService oaInfoService;


    @GetMapping("/oaCreateAssistanceContract")
    public AjaxResult oaCreatePoa(@RequestParam Map<String, Object> data) {
        //创建人
        String docNo = String.valueOf(data.get("docNo"));
        String srmUserId = String.valueOf(data.get("userId"));
        if ("".equals(docNo) || docNo == null || "null".equals(docNo)) {
            return AjaxResult.error("单据编号不能为空");
        }

        if ("".equals(srmUserId) || srmUserId == null || "null".equals(srmUserId)) {
            return AjaxResult.error("用户id不能为空");
        }
        if (oaAssistanceContractService.findAssistanceContractByDocnoType(CommonSetData.oaAssistanceContractTableMainDbNameD, docNo, "0").size() > 0) {
            return AjaxResult.error("已提交单据到OA");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        AjaxResult resData = createRequest(sdf.format(new Date()), srmUserId, docNo);
       /*if ("200".equals(resData.get("code").toString())) {
            purchaseOrderService.updateDescFlexFieldPub2ByDocNo("提交OA", docNo);
        }*/
        return resData;
    }


    /**
     * 判断是否是退回之后提交
     *
     * @param data
     * @return
     */
    @PostMapping("/oaRejSubAssistanceContract")
    public AjaxResult oaRejSubPr(@RequestBody Map<String, Object> data) {
        String requestId = (String) data.get("requestId");
        OaBillInfoVo oaInfo = oaAssistanceContractService.findAssistanceContractByRequestId(CommonSetData.oaAssistanceContractTableMainDbNameD, requestId);
        //有u9单据号退回删除
        if (oaInfo != null) {
            //如果是u9提交，u9修改状态
            System.out.println("该单据为srm创建:" + oaInfo.getSrmDocNo());
            if (StringUtils.isNotEmpty(oaInfo.getSrmDocNo())) {
                return AjaxResult.error("该单据为srm创建,不能提交已退回单据");
                // }
            } else {
                return AjaxResult.success();
            }
        }
        return AjaxResult.error();
    }

    /**
     * 创建流程入口
     *
     * @param requestnamesuffix
     * @param srmUserid
     */
    public AjaxResult createRequest(String requestnamesuffix, String srmUserid, String docNo) {

        IdentityVerifyUtil identityVerifyUtil = IdentityVerifyUtil.getInstance();
        String spk = identityVerifyUtil.getSPK();
        String secret = identityVerifyUtil.getSECRET();
        String token = identityVerifyUtil.getToken();
        if (spk == null || secret == null || token == null) {
            return null;
        }
        // BaseVo u9UserInfo = baseInfoService.findUserById(srmUserid);
        //获取Oa信息
        //  String userCode = u9UserInfo.getCode();//oa和u9编号相同
//        OaUserInfo oaUserInfo = oaInfoService.findUserInfoByCode(userCode);
        OaUserInfo oaUserInfo = oaInfoService.findUserInfoById(srmUserid);
        if (oaUserInfo == null) {
            return AjaxResult.error("OA没有该用户");
        }
        String userid = oaUserInfo.getId();
        //OaUserInfo oaUserInfo = new OaUserInfo();
        //获取u9采购头数据
        List<Map<String, String>> headcol = assistanceContractService.selectColumnsHead();
        Map<String, String> headData = assistanceContractService.selectPoHeadById(docNo);
        //获取行数据
        List<Map<String, String>> linecol = assistanceContractService.selectColumnsLine();
        List<Map<String, String>> lineData = assistanceContractService.selectPoLineById(docNo);
        //
        String url = IdentityVerifyUtil.HOST + "/api/workflow/paService/doCreateRequest";
        HttpManager http = new HttpManager();
        Map<String, String> heads = IdentityVerifyUtil.getHttpHeads(token, srmUserid, spk);
        Map<String, String> params = new HashMap<>();
        String htTitle = "合同单" + requestnamesuffix + " srm导入" + docNo;
        for (int j = 0; j < headcol.size(); j++) {
            String colName = headcol.get(j).get("name");
            if ("oatitle".equals(colName)){
                htTitle = headData.get(colName);
                continue;
            }
        }
        params.put("requestName", htTitle);
        params.put("mainData", getFormMainData(headData, headcol, oaUserInfo));
        params.put("detailData", getFormDetailData(lineData, linecol));
        params.put("workflowId", CommonSetData.oaAssistanceContractWorkflowid);
        params.put("remark", "合同单创建");
        try {
            http.cookieStore.clear();
            String res = http.postDataSSL(url, params, heads);
            if (res != null) {
                JSONObject resJson = JSONObject.parseObject(res);
                String code = String.valueOf(resJson.get("code"));

                if ("SUCCESS".equals(code)) {
                    JSONObject resdata = resJson.getJSONObject("data");
                    //填入srm单据编号S
                    oaAssistanceContractService.updateAssistanceContractSrmDocNoByRequestId(CommonSetData.oaAssistanceContractTableMainDbNameD, resdata.getString("requestid"), docNo);
                    OaBillInfoVo oninfo = oaAssistanceContractService.findAssistanceContractByRequestId(CommonSetData.oaAssistanceContractTableMainDbNameD, resdata.getString("requestid"));
                    return AjaxResult.success("操作成功", oninfo.getOaDocNo());

                } else {
                    return AjaxResult.error(resJson.getJSONObject("errMsg").toJSONString() + resJson.getJSONObject("reqFailMsg").toJSONString(), resJson.getJSONObject("errMsg").toJSONString() + resJson.getJSONObject("reqFailMsg").toJSONString());
                }
            }
            return AjaxResult.error(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 主表数据
     * <p>
     * 附件上传 包含base64, http等
     * 包含浏览框数据，单行文本数据
     *
     * @return
     */
    private String getFormMainData(Map<String, String> headData, List<Map<String, String>> headcol, OaUserInfo oaUserInfo){
        List<WorkflowRequestTableField> mainData = new ArrayList<>();

   /*     if (oaUserInfo != null) {
            //申请人  根据code查出来赋值
            WorkflowRequestTableField sqr = new WorkflowRequestTableField();
            sqr.setFieldName("sqr");
            sqr.setFieldValue(oaUserInfo.getId());
            mainData.add(sqr);
            //申请部门
            WorkflowRequestTableField sqbm = new WorkflowRequestTableField();
            sqbm.setFieldName("sqbm");
            sqbm.setFieldValue(oaUserInfo.getDepartmentid());
            mainData.add(sqbm);
            //公司
            WorkflowRequestTableField gs = new WorkflowRequestTableField();
            gs.setFieldName("gs");
            gs.setFieldValue(oaUserInfo.getSubcompanyid1());
            mainData.add(gs);
        }*/
       /* SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        WorkflowRequestTableField sqrq = new WorkflowRequestTableField();
        sqrq.setFieldName("sqrq");
        sqrq.setFieldValue(sf.format(new Date()));
        mainData.add(sqrq);*/

        for (int j = 0; j < headcol.size(); j++) {
            String colName = headcol.get(j).get("name");

            if (!"docNo".equals(colName)) {

                if ("srmid".equals(colName)) {
                    if (StringUtils.isNotEmpty(headData.get(colName))) {
                        JSONObject user = new JSONObject();
                        user.put("usercode", "admin");
                        user.put("userpwd", "d41d8cd98f00b204e9800998ecf8427e");
                        JSONObject voucher = new JSONObject();
                        voucher.put("voucherno", "focus_srm_assistance_contract");
                        JSONObject datatable = new JSONObject();
                        datatable.put("user", user);
                        datatable.put("voucher", voucher);
                        datatable.put("KeyID", headData.get(colName));
                        String data = JSON.toJSONString(datatable);
                        String srmUrl = CommonSetData.serveSrmIp + "/sysplat/dataget/data.ashx?type=webapi&optype=getvoucherfiles";
                        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                        ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
                        builder.addTextBody("data", data, contentType);
                        String result = HttpManager.sendPostFormData(srmUrl, builder,data);
                        if (StringUtils.isNotEmpty(result)) {
                            JSONObject resultmap = JSON.parseObject(result);
                            if (resultmap.getBoolean("Success")) {
                                List<Map<String, String>> fileList = new ArrayList<Map<String, String>>();
                                List<Map<String, Object>> resultfile = (List<Map<String, Object>>) resultmap.get("Result");
                                for (int g = 0; g < resultfile.size(); g++) {
                                    String filestr = String.valueOf(resultfile.get(g).get("File")).replaceAll("\r\n", "");
                                    Map<String, String> filemap = new HashMap<String, String>();
                                    filemap.put("fileName", String.valueOf(resultfile.get(g).get("Title")));
                                    filemap.put("filePath", "base64:" + filestr);
                                    fileList.add(filemap);
                                }


                                String filestrs = JSONObject.toJSONString(fileList);
                                WorkflowRequestTableField col = new WorkflowRequestTableField();
                                col.setFieldName("gzhhtfj");
                                col.setFieldValue(filestrs);
                                mainData.add(col);
                            }
                        }
                    }
                } else {
                    WorkflowRequestTableField col = new WorkflowRequestTableField();
                    col.setFieldName(colName);
                    col.setFieldValue(headData.get(colName));
                    mainData.add(col);
                }
            }

        }
        return JSONObject.toJSONString(mainData);
    }

    /**
     * 明细数据
     *
     * @return
     */
    private String getFormDetailData(List<Map<String, String>> lineData, List<Map<String, String>> lineCol) {
        List<WorkflowDetailTableInfoEntity> details = new ArrayList<>();

        //明细信息
        WorkflowDetailTableInfoEntity detail1 = new WorkflowDetailTableInfoEntity();
        detail1.setTableDBName(CommonSetData.oaAssistanceContractTableDbNameD);
        //明细数据
        List<WorkflowRequestTableRecord> detailRows = new ArrayList<WorkflowRequestTableRecord>();
        //明细行数据
        for (int i = 0; i < lineData.size(); i++) {
            WorkflowRequestTableRecord row1 = new WorkflowRequestTableRecord();
            List<WorkflowRequestTableField> rowDatas = new ArrayList<>();
            for (int j = 0; j < lineCol.size(); j++) {
                String colName = lineCol.get(j).get("name");
                if (!"docNo".equals(colName)) {
                    WorkflowRequestTableField col = new WorkflowRequestTableField();
                    col.setFieldName(colName);
                    col.setFieldValue(lineData.get(i).get(colName));
                    rowDatas.add(col);
                }
            }
            row1.setRecordOrder(0);
            row1.setWorkflowRequestTableFields(rowDatas);
            detailRows.add(row1);

        }
        detail1.setWorkflowRequestTableRecords(detailRows);

        details.add(detail1);
        return JSONObject.toJSONString(details);

    }


}
